//
//  OrderViewController.m
//  HuaLang
//
//  Created by iking on 2017/11/20.
//  Copyright © 2017年 iking. All rights reserved.
//

#import "JiFenOrderViewController.h"
#import "JiFenOrderTableViewCell.h"
#import "JiFenOrderDetailViewController.h"
#import "JiFenOrderModel.h"

@interface JiFenOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *btnArray;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation JiFenOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = tableViewBgColor;
    [self loadBaseTitleLable:@"积分订单"];
    [self setUpUI];
    self.currentPage = 1;
    self.pageSize = 20;
    self.selectIndex = 1;
    // 请求数据
    [self getGoodsListData];
    // 确认收货
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getResault:) name:@"confirmJiFenOrder" object:nil];
}
- (void)getResault:(NSNotification *)aNotification
{
    [self getGoodsListData];
}
- (void)dealloc
{
    // 注销通知
    NSLog(@"注销通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"confirmJiFenOrder" object:nil];
}
#pragma mark - 订单列表
- (void)getGoodsListData
{
    NSString *status;
    status = [NSString stringWithFormat:@"%ld",(long)self.selectIndex+1];
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/order.ashx?action=integralorderlist&companyid=%@&code=%@&timestamp=%@&pagesize=%@&pageindex=1&status=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],[NSString stringWithFormat:@"%ld",(long)self.pageSize],status] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        self.dataArray = [NSMutableArray array];
        self.currentPage = 1;
        if ([responseObject[@"status"] intValue] == 1) {
            self.dataArray = [JiFenOrderModel mj_objectArrayWithKeyValuesArray:responseObject[@"OrderList"]];
        }
        NSInteger i = [responseObject[@"OrderCount"] intValue]/self.pageSize;
        NSInteger j = [responseObject[@"OrderCount"] intValue]%self.pageSize;
        NSInteger n = 0;
        if (j > 0) {
            n = i+1;
        } else {
            n = i;
        }
        if (n<2) {
            self.tableView.mj_footer.hidden = YES;
        } else {
            self.tableView.mj_footer.hidden = NO;
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)getGoodsListDataMore
{
    self.currentPage++;
    NSString *status;
    status = [NSString stringWithFormat:@"%ld",(long)self.selectIndex+1];
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/order.ashx?action=integralorderlist&companyid=%@&code=%@&timestamp=%@&pagesize=%@&pageindex=%@&status=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],[NSString stringWithFormat:@"%ld",(long)self.pageSize],[NSString stringWithFormat:@"%ld",(long)self.currentPage],status] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        if ([responseObject[@"status"] intValue] == 1) {
            
            NSInteger i = [responseObject[@"OrderCount"] intValue]/self.pageSize;
            NSInteger j = [responseObject[@"OrderCount"] intValue]%self.pageSize;
            NSInteger n = 0;
            if (j > 0) {
                n = i+1;
            } else {
                n = i;
            }
            if (self.currentPage > n) {
                self.currentPage--;
                self.tableView.mj_footer.hidden = YES;
            } else {
                self.tableView.mj_footer.hidden = NO;
                self.dataArray = (NSMutableArray *)[self.dataArray arrayByAddingObjectsFromArray:[JiFenOrderModel mj_objectArrayWithKeyValuesArray:responseObject[@"OrderList"]]];
                [self.tableView reloadData];
            }
        } else {
            self.currentPage--;
            self.tableView.mj_footer.hidden = YES;
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)setUpUI
{
    UIButton *btn1 = [UIButton buttonWithTitle:@"未发货" fontSize:13 titleColor:UIColorWhite background:UIColorFromRGB(0xfbc865) cornerRadius:0];
    btn1.layer.borderWidth = 0.5;
    btn1.layer.borderColor = globalGray.CGColor;
    [self.view addSubview:btn1];
    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(SafeAreaTopHeight);
        make.size.mas_offset(CGSizeMake(kScreenWidth/3, rateHeight(90)));
    }];
    btn1.tag = 1;
    [btn1 addTarget:self action:@selector(actionSelect:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *btn2 = [UIButton buttonWithTitle:@"已发货" fontSize:13 titleColor:UIColorFromRGB(0x909090) background:UIColorFromRGB(0xf5f5f5) cornerRadius:0];
    btn2.layer.borderWidth = 0.5;
    btn2.layer.borderColor = globalGray.CGColor;
    [self.view addSubview:btn2];
    [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(SafeAreaTopHeight);
        make.size.mas_offset(CGSizeMake(kScreenWidth/3, rateHeight(90)));
    }];
    btn2.tag = 2;
    [btn2 addTarget:self action:@selector(actionSelect:) forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *btn3 = [UIButton buttonWithTitle:@"已签收" fontSize:13 titleColor:UIColorFromRGB(0x909090) background:UIColorFromRGB(0xf5f5f5) cornerRadius:0];
    btn3.layer.borderWidth = 0.5;
    btn3.layer.borderColor = globalGray.CGColor;
    [self.view addSubview:btn3];
    [btn3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(SafeAreaTopHeight);
        make.size.mas_offset(CGSizeMake(kScreenWidth/3, rateHeight(90)));
    }];
    btn3.tag = 3;
    [btn3 addTarget:self action:@selector(actionSelect:) forControlEvents:(UIControlEventTouchUpInside)];
    self.btnArray = [NSMutableArray array];
    [self.btnArray addObject:btn1];
    [self.btnArray addObject:btn2];
    [self.btnArray addObject:btn3];
    
    [self.view addSubview:self.tableView];
}
- (void)actionSelect:(UIButton *)btn
{
    self.selectIndex = btn.tag;
    for (UIButton *btn1 in self.btnArray) {
        if (btn1.tag != btn.tag) {
            [btn1 setBackgroundImage:[UIImage createImageWithColor:UIColorFromRGB(0xf5f5f5)] forState:UIControlStateNormal];
            [btn1 setTitleColor:UIColorFromRGB(0x909090) forState:(UIControlStateNormal)];
        } else {
            [btn1 setBackgroundImage:[UIImage createImageWithColor:UIColorFromRGB(0xfbc865)] forState:UIControlStateNormal];
            [btn1 setTitleColor:UIColorWhite forState:(UIControlStateNormal)];
        }
    }
    [self getGoodsListData];
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_dataArray.count != 0) {
        JiFenOrderModel *model = _dataArray[section];
        return model.OrderGoodsList.count;
    } else {
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JiFenOrderTableViewCell *cell = [[JiFenOrderTableViewCell alloc] init];
    if (_dataArray.count != 0) {
        JiFenOrderModel *model = _dataArray[indexPath.section];
        NSArray *array = model.OrderGoodsList;
        NSDictionary *dic = array[indexPath.row];
        [cell.goodsImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",dic[@"CartImg"]]]];
        cell.goodsTitleLB.text = dic[@"CommodityName"];
        cell.numLB.text = [NSString stringWithFormat:@"×%@",dic[@"CommodityNumber"]];
    }
    cell.selectionStyle = NO;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(180);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return rateHeight(70);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return rateHeight(110);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = UIColorWhite;
    
    UILabel *label = [UILabel labelWithText:@"" textColor:UIColorFromRGB(0x3b3b3b) fontSize:13];
    [label sizeToFit];
    [bgV addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgV);
        make.left.equalTo(bgV).offset(rateWidth(30));
    }];
    
    UILabel *label1 = [UILabel labelWithText:@"" textColor:UIColorFromRGB(0xf55555) fontSize:13];
    [label1 sizeToFit];
    [bgV addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgV);
        make.right.equalTo(bgV).offset(-rateWidth(30));
    }];
    
    UIButton *shouHuoBtn = [UIButton buttonWithTitle:@"确认收货" fontSize:14 titleColor:UIColorWhite background:navBarColor cornerRadius:0];
    [bgV addSubview:shouHuoBtn];
    [shouHuoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgV);
        make.right.equalTo(bgV).offset(-rateWidth(30));
        make.size.mas_offset(CGSizeMake(rateWidth(150), rateHeight(55)));
    }];
    shouHuoBtn.hidden = YES;
    
    // 赋值
    if (_dataArray.count != 0) {
        JiFenOrderModel *model = _dataArray[section];
        label.text = [NSString stringWithFormat:@"订单编号：%@",model.ordersNumber];
        if ([model.orderStatus intValue] == 2) {
            // 待发货
            label1.text = model.orderStatusName;
        } else if ([model.orderStatus intValue] == 3) {
            // 待收货
            label1.hidden = YES;
            shouHuoBtn.hidden = NO;
            shouHuoBtn.tag = section;
            [shouHuoBtn addTarget:self action:@selector(shouHuoAction:) forControlEvents:(UIControlEventTouchUpInside)];
        } else if ([model.orderStatus intValue] == 4) {
            // 已签收
            label1.text = model.orderStatusName;
        }
        
    }
    
    return bgV;
}
#pragma mark - 收货
- (void)shouHuoAction:(UIButton *)btn
{
    WeakSelf
    UIAlertController *alertController = [UIAlertController initWithMessage:@"是否确认收货？" bolck:^(void) {
        if (weakSelf.dataArray.count != 0) {
            JiFenOrderModel *model = weakSelf.dataArray[btn.tag];
            NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
            [MBProgressHUD showMessage:nil toView:weakSelf.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/order.ashx?action=integralordershouhuo&companyid=%@&code=%@&timestamp=%@&ordersNumber=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],model.ordersNumber] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:weakSelf.view];
                if ([responseObject[@"status"] intValue] == 1) {
                    [weakSelf.dataArray removeObject:model];
                    [weakSelf.tableView reloadData];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:weakSelf.view message:@"网络不给力..."];
            }];
        }
    } cancelBolck:^(void) {
        
    }];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = tableViewBgColor;
    UIView *whiteV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateHeight(100))];
    whiteV.backgroundColor = UIColorWhite;
    [bgV addSubview:whiteV];
    UILabel *priceLB = [UILabel labelWithText:@"" textColor:UIColorFromRGB(0xf55555) fontSize:13];
    [priceLB sizeToFit];
    [whiteV addSubview:priceLB];
    [priceLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(whiteV).offset(-rateWidth(30));
        make.centerY.equalTo(whiteV);
    }];
    UILabel *heJiLB = [UILabel labelWithText:@"所用积分：" textColor:UIColorFromRGB(0x666666) fontSize:13];
    [heJiLB sizeToFit];
    [whiteV addSubview:heJiLB];
    [heJiLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(priceLB);
        make.right.equalTo(priceLB.mas_left);
    }];
    UILabel *timeLB = [UILabel labelWithText:@"" textColor:UIColorFromRGB(0x666666) fontSize:13];
    [timeLB sizeToFit];
    [whiteV addSubview:timeLB];
    [timeLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(whiteV).offset(rateWidth(30));
        make.centerY.equalTo(priceLB);
    }];
    // 赋值
    if (_dataArray.count != 0) {
        JiFenOrderModel *model = _dataArray[section];
        priceLB.text = model.orderTotalprice;
        timeLB.text = model.orderDate;
    }
    return bgV;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArray.count != 0) {
        JiFenOrderModel *model = _dataArray[indexPath.section];
        JiFenOrderDetailViewController *jiFenOrderDetailVC = [[JiFenOrderDetailViewController alloc] init];
        jiFenOrderDetailVC.ordersNumber = model.ordersNumber;
        [self.navigationController pushViewController:jiFenOrderDetailVC animated:YES];
    }
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight+rateHeight(90)+rateHeight(2), kScreenWidth, kScreenHeight-SafeAreaTopHeight-rateHeight(90)-rateHeight(2)) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf getGoodsListData];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf getGoodsListDataMore];
        }];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
